import 'dart:async';
import 'dart:convert';
import 'dart:io';

import 'package:agora_rtc_engine/rtc_engine.dart';
import 'package:agora_rtc_engine/rtc_local_view.dart' as RtcLocalView;
import 'package:agora_rtc_engine/rtc_remote_view.dart' as RtcRemoteView;
import 'package:star_author/config/api.dart';
import 'package:star_author/config/base_configuration.dart';
import 'package:star_author/env/env_config.dart';
import 'package:star_author/generated/json/base/json_convert_content.dart';
import 'package:star_author/provider/index.dart';
import 'package:star_author/utils/common_util/log_util.dart';
import 'package:star_author/utils/common_util/shared_preferences/sp_keys_constant.dart';
import 'package:star_author/utils/common_util/shared_preferences/sp_util.dart';
import 'package:star_author/utils/common_util/toast/custom_toast.dart';
import 'package:star_author/utils/event.dart';
import 'package:star_author/utils/http/api_manager.dart';
import 'package:star_author/utils/http/http_util.dart';
import 'package:star_author/utils/live_permission_util.dart';
import 'package:star_author/utils/rong_im/rong_im.dart';
import 'package:star_author/utils/rouces_util.dart';
import 'package:star_author/utils/statistics/event/backflow_event.dart';
import 'package:star_author/utils/statistics/statistics.dart';
import 'package:star_author/utils/websocket_manage/websocket_handler.dart';
import 'package:star_author/views/products/bidding_product_list_item.dart';
import 'package:star_author/views/stream/BarrageWidget.dart';
import 'package:star_author/views/stream/model/live_good_list_entity.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:provider/provider.dart';
import 'package:rongcloud_im_plugin/rongcloud_im_plugin.dart';
import 'package:wakelock/wakelock.dart';

import '../../event_bus/global_event_bus.dart';
import '../../event_bus/live_current_good_event.dart';
import '../../event_bus/rong_im_message_event.dart';
import '../../model/backflow.dart';
import '../../model/channel.dart';
import '../../route/route_util.dart';
import '../../widgets/dialog/dialog_type.dart';
import '../../widgets/dialog/sure_dialog.dart';
import '../products/bidder_goods_detail_page/bidder_goods_detaill_page.dart';
import 'stream.dart';
import 'stream_rtc_bottom.dart';
import 'stream_rtc_controller.dart';
import 'stream_rtc_top.dart';
import 'widget/live_announcement.dart';

enum LiveForm {
  List, //列表  列表不需要显示当前商品弹框
  BidderDetail, //竞拍详情
  ConnectMicrophone, //连麦
}

class StreamSurfeceView extends StatefulWidget {
  late ClientRole clientRole;
  late String channelKey;
  late ChannelModel model;
  bool isCanClear;
  LiveForm liveForm;
  BackflowModel? data;
  int anchorId;

  StreamSurfeceView({
    Key? key,
    required this.clientRole,
    required this.channelKey,
    required this.isCanClear,
    required this.model,
    this.liveForm: LiveForm.List,
    this.data,
    this.anchorId: 0,
  }) : super(key: key);

  _StreamSurfaceViewState createState() => new _StreamSurfaceViewState();
}

class _StreamSurfaceViewState extends State<StreamSurfeceView> {
  late int _id;

  //需要记录一下开播主播的id 用来页面展示 不然连麦的时候不能区分到主播和用户的id

  TextEditingController controller = TextEditingController();

  Map<ClientRole, String> roleMap = {
    ClientRole.Broadcaster: 'host',
    ClientRole.Audience: 'audience',
  };

  bool isApply = false; //是否申请连麦了

  late StreamRTCController rtcController = Get.find<StreamRTCController>();
  late RtcEngine engine;

  initEngine() async {
    if (StreamConf.token.isEmpty) {
      await rtcController.initEngine().then((value) async {
        engine = value;
      });
    } else {
      engine = rtcController.engine;
    }
    StreamConf.engine = engine;
    engine.setEventHandler(RtcEngineEventHandler(
      joinChannelSuccess: (String channel, int uid, int elapsed) {
        update(() {
          StreamConf.joined = true;
        });
      },
      leaveChannel: (stats) {},
      userJoined: (int uid, int elapsed) {},
      userOffline: (int uid, UserOfflineReason reason) {
        if (uid == remoteUserId && reason == UserOfflineReason.Dropped) {
          setState(() {
            remoteUserId = 0;
            isConnect = false;
            CustomToast.show("当前连麦用户已掉线");
          });
        }
      },
      remoteVideoStateChanged: (
        int uid,
        VideoRemoteState state,
        VideoRemoteStateReason reason,
        int elapsed,
      ) {
        WidgetsBinding.instance!.addPostFrameCallback(
          (timeStamp) {
            update(() {
              if (widget.anchorId == uid) {
                StreamConf.uid = uid;
                StreamConf.remoteState = state;
                if (VideoRemoteState.Stopped == StreamConf.remoteState) {
                  StreamConf.uid = -1;
                  StreamConf.token = "";
                }
              } else {
                //连线的用户的返回
                Event.emit('getConnectCount', state);
                if (state == VideoRemoteState.Stopped) {
                  remoteUserId = 0;
                  isConnect = false;
                } else if ([
                  VideoRemoteState.Starting,
                  VideoRemoteState.Decoding
                ].contains(state)) {
                  //正在接受远端用户
                  remoteUserId = uid;
                  isConnect = true;
                }
              }
            });
          },
        );
      },
      error: (e) {
        LogUtil.v("$e");
      },
      clientRoleChanged: (ClientRole oldRole, ClientRole newRole) {},
      requestToken: () async {
        //更新token Token 已过期回调。
        String token2 = await _getToken(widget.channelKey);
        engine.renewToken(token2); //更新 Token。
      },
      userMuteVideo: (int userId, bool value) {
        if (userId == remoteUserId) {
          //连线
          if (value) {
            setState(() {
              remoteUserId = 0;
              isLocalView = false;
              isConnect = false;
            });
          } else {
            setState(() {
              remoteUserId = userId;
              isLocalView = true;
              isConnect = true;
            });
          }
        } else {
          if (value) {
            //离线
            setState(() {
              remoteUserId = 0;
              isLocalView = false;
              isConnect = false;
            });
          } else {
            //在线
            setState(() {
              remoteUserId = userId;
              isLocalView = true;
              isConnect = true;
            });
          }
        }
      },
    ));
    setClientRole(AudienceLatencyLevelType.LowLatency);
    if (Platform.isAndroid) {
      androidJoin();
    } else if (Platform.isIOS) {
      if (StreamConf.isJoinRongCould) {
        androidJoin();
      }
    }
    update(() {
      loading = false;
    });
  }

  //设置延迟
  setClientRole(AudienceLatencyLevelType audienceLatencyLevel) async {
    await engine.setClientRole(ClientRole.Audience,
        ClientRoleOptions(audienceLatencyLevel: audienceLatencyLevel));
  }

  update(VoidCallback fn) {
    if (mounted) {
      setState((fn));
    }
  }

  bool loading = true;

  UserProvider userProvider =
      Provider.of<UserProvider>(Get.context!, listen: false);

  List<LiveGoodListData> dataList = [];

  getCurrentGood() async {
    HttpUtil.commonRequest(
      Get.context!,
      '/api/v1/studios/${StreamConf.liveId}/backflows',
      isLoading: false,
      isErrorToast: false,
      queryParameters: {
        "explaining": true,
        "pre_page": 1,
      },
    ).then((value) {
      LiveGoodListEntity? entity =
          JsonConvert.fromJsonAsT<LiveGoodListEntity>(value.data);
      dataList = entity?.data ?? [];
      GlobalEventBus.instance.bus.fire(LiveCurrentGoodEvent(dataList));
      update(() {});
    });
  }

  bool isConnect = false; //是否连麦

  //记录进入直播间的时间
  late DateTime start_time;

  @override
  initState() {
    super.initState();
    start_time = DateTime.now();
    initStream();
    if (widget.isCanClear) {
      StreamConf.uid = -1;
      StreamConf.isJoinRongCould = true;
    }
    WidgetsBinding.instance!.addPostFrameCallback((timeStamp) async {
      this._id = userProvider.user!['id']; // 目前无法登录
      initCurrentGood();
      join();
      //直播间支持连麦
      if ((StreamConf.channelModel?.interaction ?? false)) {
        bool tip_view = SpUtil.getBool(SpKeysConstant.is_show_jian_bao_tip_view,
            defValue: true)!;
        if (tip_view) {
          setTips();
        }
      }
    });
  }

  late Timer? tipsTimer = null;

  late StreamSubscription<RongIMMessageEvent> _streamSubscriptionstream;

  int tipsCount = 5;

  setTips() {
    setState(() {
      isShowConnectTips = true;
    });
    tipsTimer = Timer.periodic(
      Duration(seconds: 1),
      (timer) {
        if (tipsCount <= 0) {
          timer.cancel();
          setState(() {
            tipsCount = 5;
            isShowConnectTips = false;
          });
        }
        tipsCount--;
      },
    );
  }

  initStream() async {
    Wakelock.enable();
    Event.on('wake_lock', (arg) async {
      bool wakelockEnabled = await Wakelock.enabled;
      Wakelock.toggle(enable: wakelockEnabled);
    });
    Event.on("close_connecting_settings", (val) {
      closeConnecting();
    });
    _streamSubscriptionstream =
        GlobalEventBus().bus.on<RongIMMessageEvent>().listen((event) async {
      if (event.message.content is TextMessage) {
        TextMessage msg = event.message.content as TextMessage;
        Map map = json.decode(msg.extra!);
        if (map.isNotEmpty) {
          if (map['operation'] == OperationKey.start_explain) {
            getCurrentGood();
          } else if (map['operation'] == OperationKey.interaction) {
            bool is_interaction = map['data']['is_interaction'];
            RongUtil.recallMessage(event.message.messageId);
            setState(() {
              StreamConf.channelModel!.interaction = is_interaction;
              if (!is_interaction) {
                isShowConnectTips = false;
                //主播关闭连麦后 直接清空本地数据 不上传
                closeConnecting();
              } else {
                setTips();
              }
              Event.emit("changed_interaction");
            });
          } else if (map['operation'] == OperationKey.connecting_mic) {
            String user_id = map['data']['user_id'].toString();
            //连接成功后删除消息这条消息 防止下一次进去直播间直接连麦
            RongUtil.recallMessage(event.message.messageId);
            isConnect = true;
            remoteUserId = int.parse(user_id);
            //判断当前连麦的人是否是自己 如果是自己才需要去mute 否则是其他人就不需要了
            if (user_id == this._id.toString() && isApply) {
              //加一个进入页面的时间判断 如果是10秒内进入页面的 并且消息推送过来了 这时候不给他连麦
              await HttpUtil.commonRequest(
                Get.context!,
                '/api/v1/studios/${StreamConf.liveId}/user_studios',
              ).then((value) {
                List data = value.data['data'] ?? [];
                int index = data.indexWhere(
                    (element) => element['connect_at'] != null); //当前连麦人员
                if (index != -1) {
                  if (data[index]['id'].toString() == this._id.toString()) {
                    //表示是自己 需要上传
                    setState(() {
                      //连接的为自己 需要开启本地视频
                      isLocalView = true;
                    });
                    Event.emit(
                      "localConnecting",
                    );
                    localSetting();
                  } else {
                    setState(() {
                      isLocalView = false;
                    });
                  }
                }
              });
            } else {
              await HttpUtil.commonRequest(
                Get.context!,
                '/api/v1/studios/${StreamConf.liveId}/user_studios',
              ).then((value) {
                List data = value.data['data'] ?? [];
                int index = data.indexWhere(
                    (element) => element['connect_at'] != null); //当前连麦人员
                if (index != -1) {
                  //有人在链接
                  setState(() {
                    isLocalView = false;
                  });
                } else {
                  //没人链接
                  setState(() {
                    isConnect = false;
                    remoteUserId = 0;
                  });
                }
              });
            }
          } else if (map['operation'] == OperationKey.close_connecting_mic) {
            String user_id = map['data']['user_id'].toString();
            //连接关闭后删除消息这条消息 防止下一次进去直播间直接连麦
            RongUtil.recallMessage(event.message.messageId);
            setState(() {
              isConnect = false;
              if (user_id == this._id.toString() && isApply) {
                //连接的为自己 需要开启本地视频
                isLocalView = false;
                remoteUserId = 0;
                closeConnecting();
                Event.emit(
                  "localCloseConnect",
                );
              } else {
                isLocalView = false;
                remoteUserId = 0;
              }
            });
          }
        }
      }
    });
  }

  closeConnecting() async {
    setState(() {
      isConnect = false;
      isLocalView = false;
      remoteUserId = 0;
      isApply = false;
    });
    setClientRole(AudienceLatencyLevelType.LowLatency);
    await engine.muteLocalVideoStream(true);
  }

  //当连麦的时候 本地需要做一些数据处理
  localSetting() async {
    await engine.setClientRole(
        ClientRole.Broadcaster,
        ClientRoleOptions(
            audienceLatencyLevel:
                AudienceLatencyLevelType.UltraLowLatency)); //修改为直播模式
    await engine.setCameraCapturerConfiguration(CameraCapturerConfiguration(
      preference: CameraCaptureOutputPreference.Manual,
      captureWidth: MyVideoDimensions.width,
      captureHeight: MyVideoDimensions.height,
      cameraDirection: CameraDirection.Rear, //后置摄像头
    ));
    await engine.setVideoEncoderConfiguration(
      VideoEncoderConfiguration(
        //视频编码的帧率(fps)，默认值为 15
        frameRate: VideoFrameRate.Fps30,
        //视频编码的最小帧率(fps)，默认值为 -1
        minFrameRate: VideoFrameRate.Fps30,
        //1280*720
        bitrate: Bitrate.b_1280_x_720_30,
        minBitrate: Bitrate.b_1280_x_720_30,
        //视频尺寸
        dimensions: VideoDimensions(
          width: MyVideoDimensions.width,
          height: MyVideoDimensions.height,
        ),
      ),
    );
    await engine.muteLocalVideoStream(false);
    // await engine.updateChannelMediaOptions();
  }

  int remoteUserId = 0;

  bool isLocalView = false;

  dispose() {
    super.dispose();
    Wakelock.disable();
    Event.off('close_connecting_settings');
    if (tipsTimer != null) {
      tipsTimer?.cancel();
    }
    backflowTimer?.cancel();
    closeConnecting();
    _streamSubscriptionstream.cancel();
    currentBackflowTimer?.cancel();
    try {
      if (StreamConf.uid == -1) {
        StreamConf.token = "";
        StreamConf.joined = false;
        StreamConf.isJoinRongCould = true;
      }
      if (!StreamConf.playing ||
          !StreamConf.isShowVideo ||
          StreamConf.uid == -1) {
        StreamConf.token = "";
        StreamConf.joined = false;
        StreamConf.isJoinRongCould = true;
        WebSocketHandle.unSubscribeLiveChannel(); //订阅
        StreamConf.remoteState = VideoRemoteState.Stopped;
        RongUtil.quitChatRoom();
        engine.leaveChannel();
        rtcController.destroy();
        API.checkIfExists(StreamConf.liveId).then((value) async {
          if (value.data['in_studio']) {
            await API.leave(StreamConf.liveId);
            StreamConf.liveId = -1;
            StreamConf.channelModel = null;
          }
        });
      } else if (Platform.isIOS) {
        StreamConf.token = "";
        StreamConf.joined = false;
        StreamConf.isJoinRongCould = true;
        WebSocketHandle.unSubscribeLiveChannel(); //订阅
        StreamConf.remoteState = VideoRemoteState.Stopped;
        RongUtil.quitChatRoom();
        engine.leaveChannel();
        rtcController.destroy();
      }
    } catch (e) {}
    if (timer != null) {
      timer?.cancel();
    }
  }

  Color color = Colors.white;

  Widget loadingView(String text) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.center,
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        StreamLoadingWidget(),
        SizedBox(
          height: 10.w,
        ),
        Center(
          child: Text(
            text,
            style: TextStyle(
              color: ColorConf.white,
              fontSize: 18.sp,
            ),
          ),
        )
      ],
    );
  }

  Widget renderSurfaceView() {
    if (widget.clientRole == ClientRole.Audience) {
      if (StreamConf.joined && StreamConf.playing) {
        return RtcRemoteView.SurfaceView(
          channelId: widget.channelKey,
          uid: StreamConf.uid,
          renderMode: StreamConf.renderMode,
        );
        // return Container();
      } else if (StreamConf.joined && !StreamConf.playing) {
        color = Colors.white;
        return loadingView('加载中...');
      } else if (StreamConf.joined &&
          !StreamConf.playing &&
          VideoRemoteState.Stopped == StreamConf.remoteState) {
        return loadingView('主播已下播~');
      } else {
        color = Colors.white;
        return loadingView('加载中...');
      }
    } else {
      return SizedBox.shrink();
    }
  }

  buildLocalView() {
    if (isConnect) {
      if (isLocalView) {
        //本地用户
        return Container(
          width: ScreenUtil().screenWidth,
          height: ScreenUtil().screenHeight,
          child: RtcLocalView.SurfaceView(
            renderMode: VideoRenderMode.Hidden,
            mirrorMode: StreamConf.videoMirrorMode,
          ),
        );
      } else {
        //远端用户
        return Container(
          width: ScreenUtil().screenWidth,
          height: ScreenUtil().screenHeight,
          child: RtcRemoteView.SurfaceView(
            channelId: widget.channelKey,
            uid: remoteUserId,
            renderMode: StreamConf.renderMode,
          ),
        );
      }
    } else {
      return Container(
        child: renderSurfaceView(),
        width: double.infinity,
        color: ColorConf.normal,
        height: ScreenUtil().screenHeight,
      );
    }
    return Container();
  }

  Future<String> _getToken(String channelKey) async {
    dynamic res = await API.getRTCToken({
      'role': roleMap[widget.clientRole],
      'uid': this._id,
      'channel_name': channelKey,
    });
    dynamic token = res.data['token'];
    return token;
  }

  late Timer? timer = null;

  int timer_count = 3;

  joinRongCould() {
    RongUtil.connect(
      () async {
        await RongUtil.joinChatRoom();
      },
      "user",
    );
  }

  Future join() async {
    await initEngine();
    WebSocketHandle.subscribeLiveChannel();
    RongIMClient.onJoinChatRoom = (String? targetId, int? status) {
      if (status == RCOperationStatus.Success) {
        RongUtil.joinChatRoomEvent(
            Provider.of<UserProvider>(Get.context!, listen: false));
        StreamConf.isJoinRongCould = false;
      } else if (status == RCOperationStatus.Failed) {
        if (Get.currentRoute == "/StreamPage") {
          Future.delayed(Duration(seconds: 10), () {
            //当前页面才需要
            RongUtil.joinChatRoom();
          });
        }
      } else if (status == 23410) {
        if (EnvConfig.isProd()) {
          CustomToast.show('当前直播间未开播!');
        }
      }
    };
    if (StreamConf.isJoinRongCould) {
      joinRongCould();
      //token 空的时候 需要连接
      await HttpUtil.commonRequest(
        Get.context!,
        ApiManager.studios + "/${StreamConf.liveId}/check_if_exists",
        isErrorToast: false,
        isLoading: false,
      ).then(
        (value) async {
          if (!value.data['in_studio']) {
            //{in_studio: false}
            await API.join(StreamConf.liveId);
          } else {
            if (!StreamConf.isShowVideo) {
              //是否小窗口
              await API.leave(StreamConf.liveId);
              await API.join(StreamConf.liveId);
            }
          }
        },
      );
      StreamConf.isShowVideo = true; //进来需要初始化 默认
    }

    if (mounted) {
      update(() {});
    }
  }

  initCurrentGood() {
    if (widget.data != null) {
      if (widget.data?.status == "evaluation") {
        isShowBackFlowInfo = true;
      }
      update(() {});
    }
    backflowTimer = Timer.periodic(Duration(seconds: 1), (timer) {
      backflowCount--;
      if (backflowCount <= 0) {
        timer.cancel();
        backflowTimer?.cancel();
        isShowBackFlowInfo = false;
        update(() {});
      }
    });
    getCurrentGood();
  }

  androidJoin() async {
    String token = await _getToken(widget.channelKey);
    StreamConf.token = token;
    try {
      await engine.leaveChannel();
      await engine.joinChannel(
        StreamConf.token,
        StreamConf.channelKey,
        null,
        _id,
        ChannelMediaOptions(
          publishLocalAudio: false,
          publishLocalVideo: false,
        ),
      );
      await engine.muteAllRemoteVideoStreams(false);
    } catch (error) {
      dynamic _e = error;
      if (['-17', '-5', '5'].contains(_e.code)) {
        engine.leaveChannel();
        String token2 = await _getToken(widget.channelKey);
        StreamConf.token = token2;
        await engine.joinChannel(
          StreamConf.token,
          StreamConf.channelKey,
          null,
          _id,
          ChannelMediaOptions(),
        );
      }
    }
  }

  bool isClear = false; //点击清屏

  FocusNode focusNode = FocusNode();

  buildSmallView() {
    if (isConnect) {
      return Container(
        width: 90.w,
        height: 130.w,
        color: Colors.black,
        child: Container(
          child: renderSurfaceView(),
          width: double.infinity,
          color: ColorConf.normal,
          height: ScreenUtil().screenHeight,
        ),
      );
    }
    return Container();
  }

  close(bool needBack) {
    if (isLocalView && isConnect) {
      //表示是本地用户要退出这个页面 需要给个弹框
      DialogUtil.showMyDialog(
          dialogType: DialogType.Disconnect,
          rightButtonOnTap: () {
            closeConnecting();
            engine.leaveChannel();
            Get.back();
          });
    } else if (needBack) {
      Get.back();
    } else if (!needBack) {
      LivePermissionUtil.checkSystemAlertWindowPermission((isGranted) {
        if (isGranted) {
        } else {
          StreamConf.uid = -1;
        }
        Get.back();
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
        child: Scaffold(
          body: GestureDetector(
            onTap: () {
              if (focusNode.hasFocus) {
                FocusScope.of(context).unfocus(); //失去焦点
              } else {
                isClear = !isClear;
                update(() {});
              }
            },
            child: Container(
              height: double.infinity,
              width: double.infinity,
              child: Stack(
                children: [
                  SingleChildScrollView(
                    child: buildLocalView(),
                  ),
                  Positioned(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      mainAxisAlignment: MainAxisAlignment.start,
                      children: [
                        StreamRtcTop(
                          model: widget.model,
                          liveForm: widget.liveForm,
                          isClear: isClear,
                          callBack: () {
                            close(true);
                          },
                        ),
                        Container(
                          child: LiveAnnouncement(
                            isClear: isClear,
                          ),
                          margin: EdgeInsets.only(
                            top: 10.w,
                          ),
                        )
                      ],
                    ),
                    left: 12.w,
                    right: 12.w,
                    top: MediaQuery.of(context).padding.top + 20.w,
                  ),
                  if (!isClear) buildCurrentBackFlowGood(),
                  Positioned(
                    child: Container(
                      height: Get.height, //屏幕高度
                      width: Get.width,
                      alignment: Alignment.bottomLeft,
                      child: SingleChildScrollView(
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          mainAxisAlignment: MainAxisAlignment.end,
                          children: [
                            Offstage(
                              child: barrageList(
                                liveFrom: LiveFrom.User,
                                liveForm: widget.liveForm,
                              ),
                              offstage: isClear,
                            ),
                            StreamRtcBottom(
                              controller: controller,
                              isClear: isClear,
                              focusNode: focusNode,
                              anchorId: widget.anchorId,
                              applyCallBack: (apply) {
                                setState(() {
                                  isApply = apply;
                                });
                              },
                            ),
                          ],
                        ),
                      ),
                    ),
                  ),
                  connectTipsWidget(),
                  Positioned(
                    child: buildSmallView(),
                    bottom: MediaQuery.of(context).padding.bottom +
                        7.w +
                        50.w +
                        12.w,
                    right: 12.w,
                  )
                ],
              ),
            ),
          ),
        ),
        onWillPop: () {
          close(false);
          return Future.value(false);
        });
  }

  bool isShowBackFlowInfo = false; //是否显示底部竞拍弹出框

  Timer? backflowTimer; //

  Timer? currentBackflowTimer; //

  int backflowCount = 15;

  bool isShowConnectTips = false;

  //可连麦弹出框
  //ic_can_connect_bg
  //ic_can_connect_close
  Widget connectTipsWidget() {
    if ((StreamConf.channelModel?.interaction ?? false) && isShowConnectTips) {
      return Positioned(
        child: Container(
          height: 30.w,
          width: 158.w,
          child: Stack(
            children: [
              Image.asset(
                RoucesUtil.getAssets('ic_can_connect_bg'),
              ),
              Container(
                alignment: Alignment.center,
                margin: EdgeInsets.only(bottom: 4.w),
                child: Text(
                  '连麦已开放，可申请连麦鉴宝',
                  style: TextStyle(fontSize: 12.sp, color: Color(0xFF8B572A)),
                ),
              ),
              Positioned(
                child: GestureDetector(
                  child: Container(
                    alignment: Alignment.topRight,
                    child:
                        RoucesUtil.getAssetsIcon('ic_can_connect_close_lt', 14.sp),
                    width: 24.w,
                    height: 24.w,
                  ),
                  behavior: HitTestBehavior.opaque,
                  onTap: () {
                    setState(() {
                      isShowConnectTips = false;
                      SpUtil.putBool(
                          SpKeysConstant.is_show_jian_bao_tip_view, false);
                    });
                  },
                ),
                top: 0,
                right: 0,
              ),
            ],
          ),
        ),
        bottom: MediaQuery.of(context).padding.bottom + 7.w + 40.w + 12.w,
        right: 20.w,
      );
    }
    return Container();
  }

  //当前正在讲解的商品
  buildCurrentBackFlowGood() {
    if (remoteUserId != 0 || isLocalView) {
      //有连麦
      return Container();
    }
    if (dataList.length == 0) {
      return Container();
    }
    if ((dataList[0].hasEvaluated ?? false)) {
      return Container();
    }
    DecorationImage decorationImage = DecorationImage(
      scale: 2,
      image: const AssetImage('images/lt_common/temp_load.png'),
    );
    if ((dataList[0].goods?.cover?.url ?? "").isEmpty) {
      decorationImage = DecorationImage(
        scale: 2,
        image: const AssetImage('images/lt_common/temp_load.png'),
      );
    } else {
      decorationImage = DecorationImage(
          image: NetworkImage(dataList[0].goods?.cover?.url ?? ""),
          fit: BoxFit.cover);
    }
    return Positioned(
      child: GestureDetector(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Stack(
              children: [
                Container(
                  width: 48.w,
                  height: 48.w,
                  decoration: BoxDecoration(
                      borderRadius: BorderRadius.only(
                        topLeft: Radius.circular(4.w),
                        topRight: Radius.circular(4.w),
                      ),
                      image: decorationImage),
                ),
                Positioned(
                  child: Container(
                    width: 48.w,
                    color: Color(0x4D000000),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Image.asset(
                          'images/video_loading_lt.gif',
                          width: 7.w,
                          height: 7.w,
                        ),
                        SizedBox(
                          width: 3.w,
                        ),
                        Text(
                          '讲解中',
                          style: TextStyle(
                            fontSize: 8.sp,
                            color: Colors.white,
                          ),
                        )
                      ],
                    ),
                  ),
                  bottom: 0,
                )
              ],
            ),
            Container(
              width: 48.w,
              height: 23.w,
              alignment: Alignment.center,
              child: Stack(
                children: [
                  Image.asset(
                    RoucesUtil.getAssets('ic_current_bidder_msg_lt'),
                    width: 48.w,
                    height: 23.w,
                    fit: BoxFit.cover,
                  ),
                  Container(
                    alignment: Alignment.center,
                    margin: EdgeInsets.only(bottom: 3.w),
                    child: Text(
                      "出个价",
                      style: TextStyle(
                          fontSize: 12.sp,
                          fontWeight: FontWeight.w500,
                          color: Colors.white),
                    ),
                  )
                ],
              ),
            ),
          ],
        ),
        onTap: () {
          RouteUtil.checkLogin(context, () {
            bool result = userProvider.isBidder;
            //判断是否有保证金
            if (!userProvider.isWhite) {
              if (!result) {
                result = false;
                DialogUtil.showMyDialog(
                    dialogType: DialogType.toPayBond,
                    leftButtonOnTap: () {},
                    rightButtonOnTap: () {});
              } else {
                result = true;
              }
            } else {
              result = true;
            }
            if (result) {
              StatisticsUtil.event(BiddingLiveEvent.offer, getUMengMap({}));
              Get.to(
                      BidderGoodsDetailPage(
                        id: dataList[0].id ?? 0,
                        formDetail: BiddingProductListItemFormType.Live,
                        isNeedShowPriceDialog: true,
                      ),
                      preventDuplicates: false)!
                  .then((value) async {
                if (value != null) {
                  await getCurrentGood();
                }
              });
            }
          });
        },
      ),
      bottom: MediaQuery.of(context).padding.bottom + 7.w + 40.w + 12.w,
      right: 12.w,
    );
  }
}
